package br.edu.udc.sistemas.ia5.util;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Vector;

import br.edu.udc.sistemas.ia5.annotation.Column;
import br.edu.udc.sistemas.ia5.annotation.Entity;
import br.edu.udc.sistemas.ia5.annotation.Id;
import br.edu.udc.sistemas.ia5.annotation.Table;

public class Reflection {

	private static void validate(Class<?> c) throws Exception {
		if (!c.isAnnotationPresent(Entity.class)) {
			throw new Exception();
		}
		if (!c.isAnnotationPresent(Table.class)) {
			throw new Exception();
		}
	}

	public static Table getTable(Class<?> c) throws Exception {
		validate(c);
		return (Table) c.getAnnotation(Table.class);
	}


	public static Field getIdField(Class<?> c) throws Exception {
		validate(c);
		Field fieldList[] = c.getDeclaredFields();
		for (int i = 0; i < fieldList.length; i++) {
			Field field = fieldList[i];
			if ((field.isAnnotationPresent(Id.class)) &&
				(field.isAnnotationPresent(Column.class))) {
				field.setAccessible(true);
				return field;
			}
		}
		throw new Exception();
	}

	public static Field[] getFields(Class<?> c) throws Exception {
		validate(c);
		Field fieldList[] = c.getDeclaredFields();
		Collection<Field> result = new Vector<Field>();
		for (int i = 0; i < fieldList.length; i++) {
			Field field = fieldList[i];
			if (field.isAnnotationPresent(Column.class)) {
				field.setAccessible(true);
				result.add(field);
			}
		}
		return (Field[]) result.toArray(new Field[result.size()]);
	}
}